package com.netease.financial.module.browser;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.netease.financial.R;
import com.netease.financial.common.util.HttpUtils;
import com.netease.financial.common.util.NfsLog;
import com.netease.financial.internal.di.components.BrowserComponent;
import com.netease.financial.internal.di.components.DaggerBrowserComponent;
import com.netease.financial.internal.di.modules.ActivityModule;
import com.netease.financial.internal.di.modules.BrowserModule;
import com.netease.financial.ui.activity.BaseAppCompatActivity;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by laizhenqi on 16/8/2.
 */
public class BrowserActivity extends BaseAppCompatActivity implements BrowserView {

    private final static String TAG = BrowserActivity.class.getSimpleName();

    public final static String EXTRA_BROWSER_URL = "browser_url";

    BrowserComponent mComponent;

    @Inject
    BrowserPresenter mPresenter;

    @Bind(R.id.webView_browser)
    WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_browser);
        ButterKnife.bind(this);

        initialize();
        handleIntent(getIntent());
    }

    private void initialize() {
        initializeInjector();
        initializePresenter();
        initializeActionbar();
        initWebView();
        initWebChromeClient();
        initWebViewClient();
    }

    private void initializeInjector() {
        mComponent = DaggerBrowserComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .browserModule(new BrowserModule())
                .build();
        mComponent.inject(this);
    }

    private void initializePresenter() {
        mPresenter.setView(this);
        mPresenter.initialize();
    }

    private void initializeActionbar() {
        enableLeftNavigationItem(true);
        getCloseNavigationItem().setVisibility(View.VISIBLE);
        getCloseNavigationItem().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initWebView() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // 在user agent中增加应用信息，服务器端可以从user agent中获取此信息
        String defaultUserAgent = webSettings.getUserAgentString();
        String extraHeader = HttpUtils.getExtraHeader(getApplicationContext());
        webSettings.setUserAgentString(defaultUserAgent + extraHeader);

        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        /***打开本地缓存提供JS调用**/
        webSettings.setDomStorageEnabled(true);
        // Set cache size to 8 mb by default. should be more than enough
//        webSettings.setAppCacheMaxSize(1024*1024*8);

        //让WebView 支持ViewPort的缩放
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setUseWideViewPort(true);

        mWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                    return true;
                }
                return false;
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(NfsLog.DEBUG_MODE);
        }

    }

    private void initWebChromeClient() {
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

        });
    }

    private void initWebViewClient() {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                mWebView.loadUrl(url);
                return true;
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.onResume();
    }

    @Override
    protected void onPause() {
        mPresenter.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        ButterKnife.unbind(this);
        mPresenter.onDestroy();
        super.onDestroy();
    }

    private void handleIntent(@NonNull Intent intent) {
        String url = intent.getStringExtra(EXTRA_BROWSER_URL);
        mWebView.loadUrl(url.substring(url.indexOf("fc://") + 5));
        NfsLog.i(TAG, mWebView.getUrl());
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onSuccess() {

    }

    @Override
    public void onError() {

    }
}
